package com.wyb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyb.mapper.ArticleMapper;
import com.wyb.mapper.UserMapper;
import com.wyb.pojo.Article;
import com.wyb.pojo.Message;
import com.wyb.mapper.MessageMapper;
import com.wyb.constant.Result;
import com.wyb.pojo.User;
import com.wyb.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author wyb
 * @since 2023-02-26
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result getMessage(int userId) {
        LambdaQueryWrapper<Message> lqw = new LambdaQueryWrapper();
        lqw.eq(Message::getUserId, userId);
        lqw.orderByDesc(Message::getCreateTime);
        List<Message> messages = messageMapper.selectList(lqw);
        List<Map<String, Object>> list = new ArrayList(20);


        for (Message message : messages) {
            Map<String, Object> map = new HashMap();

            String type = "";
                switch (message.getTypeId()){
                    case 1: type = "赞了你的博文"; break;
                    case 2: type = "赞了你的评论"; break;
                    case 3: type = "收藏了你的博文"; break;
                    default:  type = "他什么也没做" ;
                }
                map.put("type", "赞了你的博文");
                map.put("message", message);
            User user = userMapper.selectById(message.getLikedUserId());

            map.put("nickName",user.getNickName());
            map.put("avatar", user.getAvatar());

            Article article = articleMapper.selectById(message.getTopicId());
            map.put("articleTitle", article.getArticleTitle());
            map.put("authorId",article.getUserId());
            map.put("articleId",article.getId());
            list.add(map);

        }
        return list.isEmpty() ? new Result(201, "未获取到消息", list)
                                : new Result(200, "成功获取到消息",list);
    }

    @Override
    public Result deleteMessage(int id) {

        int i = messageMapper.deleteById(id);
        return i == 0 ? new Result(201, "消息删除失败", null)
                        : new Result(200, "消息删除成功",  null);
    }

    @Override
    public Result deleteMessages(int userId) {

        LambdaQueryWrapper<Message> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Message::getLikedUserId, userId);

        int delete = messageMapper.delete(lqw);

        return delete == 0 ? new Result(201, "消息清空失败", null)
                                : new Result(200,  "消息清空完成", null);
    }
}
